# _*_ coding=utf-8 _*_
# import inter
import pub
import config
# import traceback
import urllib
import os
# import sys
import json
from reportlab.lib.pagesizes import A4, landscape
from reportlab.pdfgen import canvas
from PIL import Image
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
import huilian_selenium


class FileTools():

    '''图片转PDF'''

    def transferPdf(self, dstpath, pdf_name, fileList):
        #lp = 'D:/python27_file_down/260/185/';
        # 将一个目录下所有图片生成一个pdf
        # fileList=[lp+'1539695151688passport.jpg',lp+'1539695157975Old_Passport.jpg'];
        # 判断如果不存在这个路径就创建这个路径
        if not os.path.exists(dstpath):
            os.makedirs(dstpath)
        pass
        self.createPdf(os.path.join(dstpath, pdf_name + '.pdf'), fileList)
    pass

    '''
            创建PDF文件
            需要预告安装支持中文的字体，如simfang从win拷贝过来安装
    '''

    def createPdf(self, dstpath, fileList):
        img = Image.open(fileList[0].decode('UTF-8'))
        c = canvas.Canvas(dstpath, img.size)  # 第一张图片的尺寸新建pdf

        pdfmetrics.registerFont(TTFont('simfang', 'simfang.ttf'))  # 注册字体
        fontheight = 15
        c.setFont('simfang', fontheight)
        #c.drawString(100, 300, u'宋体宋体')
        height = fontheight
        num = 1
        '''
                        不需要输出文件名称列表
        for i in fileList:#标明本pdf的文件列表
            c.drawString(fontheight,height,str(num)+"/"+str(len(fileList)));
            c.drawString(fontheight+50, height, os.path.split(i)[1]);
            num+=1;
            height+=fontheight;
        c.showPage();
        '''

        for i in fileList:
            c.drawImage(i.decode('UTF-8'), 0, 0)  # 转换为中文路径名称打开
            c.showPage()
        c.save()
    pass

    '''下载文件'''

    def down_file(self, url, local_path, app_id, now_down_index, count):
        # 检查目录是否存在,不存在就创建目录
        if not os.path.exists(local_path):
            os.makedirs(local_path)
        pass
        filepath, shotname, extension = self.jwkj_get_filePath_fileName_fileExt(url)
        self.app_id = app_id
        self.filename = shotname + extension
        self.local_path = local_path
        self.now_down_index = now_down_index
        self.count = count
        local = os.path.join(self.local_path, self.filename)
        urllib.urlretrieve(url, local, self.Schedule)
    pass

    '''获取文件路径、文件名、后缀名'''

    def jwkj_get_filePath_fileName_fileExt(self, filename):
        (filepath, tempfilename) = os.path.split(filename)
        (shotname, extension) = os.path.splitext(tempfilename)
        return filepath, shotname, extension
    pass

    '''下载输出百分比'''

    def Schedule(self, dbnum, dbsize, size):
        # dbnum:已经下载的数据块
        # dbsize:数据块的大小
        # size:远程文件的大小
        print_true = False
        per = 100.0 * dbnum * dbsize / size
        if per > 100:
            per = 100
        pass
        if per >= 20 and per < 21:
            print_true = True
        # elif per >= 40 and per < 41:
            # print_true = True;
        elif per >= 60 and per < 61:
            print_true = True
        # elif per >= 80 and per < 81:
            # print_true = True;
        elif per >= 100:
            print_true = True
        pass
        if print_true:
            # pub.pub.log(self.app_id, '(' + str(self.now_down_index) + '/' +str(self.count) + ')(' + self.filename + ') === ' + '%.2f%%' % per, "")
            pub.pub.log('{} ({}/{})({}) === {:.2f}'.format(self.app_id, self.now_down_index, self.count, self.filename, per))
        pass

    pass

    # 填写附加表
    def newZealand_fillINZ1027(self, app, app_lang, live_address, current_work, extra_list, family_list, out_puth):
        # 因为这里没有继承关系,所以需要重新赋值一次
        if app["parent_app_id"] and app["parent_app_relation"] == 2 and pub.age(app["birthday"]):
            pub.pub.log(app["id"], "不需填写1027表", "18岁以下的未成年子女无需填写")
            return True
        # try:
        pub.pub.log(app["id"], "开始填写新西兰签证附加表(INZ1027表)", "")

        data = {}
        ########## P1 #########
        # 基本信息
        data["p1-FullName"] = app['passport_surnames'] + \
            "  " + app['passport_given_names']  # 姓名
        # 出生日期
        data['p1-birthday'] = self.newZealand_date_format(app['birthday'])
        data['p1-sex-' + str(app['sex'])] = "Y"  # 性别
        # 是否有曾用名
        if(app['has_used_names']):
            data['p1-OtherName'] = app_lang['lang_used_surnames'] + \
                " " + app_lang['lang_used_given_names']
        data['p1-PlaceOfBirth'] = app_lang['lang_birth_province']  # 出生地
        # 国籍
        data['p1-Citizenship'] = pub.get_base_country_english_name(
            app['nationality'])
        # 出生国家
        data['p1-CountryOfBirth'] = pub.get_base_country_english_name(
            app['birth_country_id'])
        data['p1-ChineseNationalIDNumber'] = app["id_number"]  # 身份证号码
        data['p1-PassportNumber'] = app['passport_number']  # 护照号码
        # 签发日期
        data['p1-DateOfIssue'] = self.newZealand_date_format(
            app['passport_starttime'])
        # 到期日期
        data['p1-DateOfExpire'] = self.newZealand_date_format(
            app['passport_endtime'])
        # 居住地址和联系方式
        if not live_address:
            pub.pub.log(app["id"], "填表失败", "未能获取居住地址")
            return False
        data['p1-RoomNo'] = live_address['addr_room_number']  # 门牌号
        if live_address["addr_unit_number"]:
            data['p1-EntranceNo'] = live_address['addr_unit_number']  # 单元号
        data['p1-BuildingNo'] = live_address['addr_building_number']  # 楼号
        data['p1-StreetNo'] = live_address['addr_street_number']  # 街道号
        data['p1-communityname'] = live_address['lang_addr_community']  # 小区名称
        data['p1-StreetName'] = live_address['lang_addr_street_name']  # 街道名
        data['p1-District'] = live_address['lang_district']  # 区域
        data['p1-City'] = live_address['lang_city']  # 城市
        data['p1-Province'] = live_address['lang_province']  # 省份
        data['p1-Telephone'] = app['mobile']  # 电话
        if app['email']:
            data['p1-Email'] = app['email']  # Email
        # 工作单位
        if app["work_status"] in [11401, 11402, 11403]:
            current_work = current_work
            data['p1-Occupation'] = current_work['lang_title']
            data['p1-NameOfCompany'] = current_work['lang_group_name']
            data['p1-work-BuildingName'] = current_work['lang_addr_community']
            data['p1-work-StreetNo'] = "No." + \
                str(current_work['addr_street_number'])
            data['p1-work-StreetName'] = current_work['lang_addr_street_name']  # 街道名
            data['p1-work-District'] = current_work['lang_district']  # 区域
            data['p1-work-City'] = current_work['lang_city']  # 城市
            data['p1-work-Province'] = current_work['lang_province']  # 省份
            data['p1-work-Telephone'] = current_work['tel']  # 电话
        # 是否获得过高等教育
        if app["has_education"]:
            edu = pub.list_find_one(
                extra_list, {"extra_type": 2, "is_current": 0})
            data['p1-Edu-Programme'] = edu['lang_title']
            data['p1-Edu-SchoolName'] = edu['lang_group_name']
            data['p1-Edu-Dates'] = "From " + self.newZealand_date_format(
                edu['start_date'], "%d/%m/%Y") + " to " + self.newZealand_date_format(edu['end_date'], "%d/%m/%Y")
        ########## P2 #########
        # 服兵役史
        military_list = pub.list_find_all(extra_list, {"extra_type": 7})
        for i in range(0, len(military_list)):
            num = str(i)
            extra = military_list[i]
            data['p2-Rank' + num] = extra['lang_military_rank']
            data['p2-Unit' + num] = extra['lang_group_name']
            data['p2-Service' + num] = extra['lang_military_branch']
            data['p2-DatesServed' + num] = "From " + self.newZealand_date_format(
                extra['start_date'], "%d/%m/%Y") + " to " + self.newZealand_date_format(extra['end_date'], "%d/%m/%Y")
        # 家庭成员
        family_list = pub.list_find_all(family_list, {"type": [0, 3]})
        for i in range(0, len(family_list)):
            num = str(i + 1)
            family = family_list[i]
            data['p2-Name' + num] = family['lang_surnames'] + \
                " " + family['lang_given_names']
            data['p2-Relationship' + num] = pub.get_base_option_desc(family['relation'])
            data['p2-Dateofbirth' + num] = self.newZealand_date_format(family['birthday'], "%d/%m/%Y")
        # 签证类型
            # if parent_app["visa_type"] in [1]:
            #     data['p2-Tourism']  = "Y"
            # elif parent_app["visa_type"] in [5]:
            #     data['p2-Business']  = "Y"
            # elif parent_app["visa_type"] in [3]:
            #     data['p2-Study']    = 'Y'
            # elif parent_app["visa_type"] in [3]:
            #     data['p2-Study']    = 'Y'
            # else:
            #     data['p2-Other']         = "Y"
            #     data['p2-Othertext']    = pub.get_base_visa_type_name_en(parent_app["visa_type"])
        # 暂时来说只支持旅游签证类型
        data['p2-Tourism'] = "Y"
        # 抵达时间
        data['p2-Dateofarrival'] = self.newZealand_date_format(
            app["arrival_time"])
        # 离开时间
        data['p2-Dateofdeparture'] = self.newZealand_date_format(
            app["departure_time"])

        # print encodedjson
        dir = config.config.get("BASE", "HTML2PDF_DIR") + '/nzl_visa_template/'
        template = dir + 'INZ1027.pdf'
        targetFileName = "1027.pdf"
        # 测试
        # if self.is_test:
        #     targetFileName = "output.pdf";
        # 组装输出路径
        out_puth = out_puth + 'pdf/'
        # 判断如果不存在这个路径就创建这个路径
        if not os.path.exists(out_puth):
            os.makedirs(out_puth)
        target = out_puth + targetFileName
        # 生成pdf文件
        if self.fill_pdf_file(template, target, data, app["id"], True):
            #                 if not self.is_test:
            #                     if upload_app_file(self.app_id, "INZ1027", "1027附加表", target):
            #                         return True
            #                     else:
            #                         return False
            return True
        else:
            return False
    pass

    def fill_pdf_file(self, template, target, data, app_id, isUpper, isEditable=True, marginx=0, marginy=0):
        if isUpper:
            # 将所有的值转化为大写
            keys = data.keys()
            for j in range(0, len(keys)):
                # 若为None则设置为空字符串
                if data[keys[j]] is None:
                    data[keys[j]] = ""
                pass
                if(data[keys[j]]):
                    data[keys[j]] = data[keys[j]].upper()
                pass
            pass
        pass
        encodedjson = json.dumps(data)
        encodedjson = urllib.quote(encodedjson)
        JAVA_COMMAND = config.config.get("BASE", "JAVA_COMMAND")
        FILL_PDF_JAR = config.config.get("BASE", "FILL_PDF_JAR")
        editable = "true" if isEditable else "false"
        str_list = [JAVA_COMMAND, "-jar", FILL_PDF_JAR, "--input", template, "--output", target,
                    "--data", encodedjson, "--canedit", editable, "--marginx", str(marginx), "--marginy", str(marginy)]
        res = huilian_selenium.Tools().cmd_run(str_list)
        if "SUCCESS" in res:
            pub.log(app_id, "生存成功", res)
            return True
        else:
            pub.log(app_id, "生存Pdf文件失败", res)
            return False
    pass

    # 时间格式化

    def newZealand_date_format(self, date, format="%d  %m    %Y"):
        y = date.strftime("%Y")
        m = date.strftime("%m")
        d = date.strftime("%d")
        d = d[0:1] + " " + d[1:2]
        m = m[0:1] + " " + m[1:2]
        y = y[0:1] + "  " + y[1:2] + "  " + y[2:3] + "  " + y[3:4]
        str = d + "    " + m + "    " + y
        return str
    pass
